package com.gyt.manager.conf.datasource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 投放系统报表数据源配置
 * @author v_yantgao
 *
 */
@Configuration
@MapperScan(basePackages = "com.gyt.manager.dao.test", sqlSessionTemplateRef  = "testSqlSessionTemplate")
public class TestDataSourceConfig {

	private static Logger logger = LoggerFactory.getLogger(TestDataSourceConfig.class);

	/**
	 * 数据源
	 * @return
	 */
	@Bean(name = "testDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.test")
    public DataSource testDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

	/**
	 * 然后创建 SqlSessionFactory
	 * @param dataSource
	 * @return
	 * @throws Exception
	 */
    @Bean(name = "testSqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("testDataSource") DataSource dataSource){
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        try {
			bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:config/mapper/test/*.xml"));
			return bean.getObject();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
        return null;
    }

    /**
     * 创建事务管理器
     * @param dataSource
     * @return
     */
    @Bean(name = "testTransactionManager")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("testDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }


    /**
     * 包装到 SqlSessionTemplate 中
     * @param sqlSessionFactory
     * @return
     * @throws Exception
     */
    @Bean(name = "testSqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("testSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    /**
     * 初始化对应的spring jdbc对象
     * @param dataSource
     * @return
     */
    @Bean(name = "testJdbcTemplate")
    public JdbcTemplate testJdbcTemplate(@Qualifier("testDataSource") DataSource dataSource){
    	return new JdbcTemplate(dataSource);
    }
}
